import React, { Component } from 'react';
import { Card, Button,  Modal, Form, Input, Row, Col, Select, Radio, Table, Upload, Icon, Popconfirm, message } from 'antd';
import { connect } from 'dva';


import styles from './style.less';


const selectOptions = [
    { value: '01、医疗设备、器械类', key: '医疗设备、器械类' },
    { value: '02、学校功能设备类', key: '学校功能设备类' },
    { value: '03、监控设备及系统类', key: '监控设备及系统类' },
    { value: '04、公安消防设备类', key: '公安消防设备类' },
    { value: '05、教育典教类', key: '教育典教类' },
    { value: '06、车辆交通类', key: '车辆交通类' },
    { value: '07、纺织类', key: '纺织类' },
    { value: '08、信息系统集成类', key: '信息系统集成类' },
    { value: '09、办公家具类', key: '办公家具类' },
    { value: '10、体育健身类', key: '体育健身类' },
    { value: '11、其他类', key: '其他类' }
]
const children = []
selectOptions.forEach(v => {
    children.push(<Select.Option value={v.key}>{v.value}</Select.Option>)
})

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}



const EditModal = Form.create()(
    // eslint-disable-next-line react/prefer-stateless-function
    class extends React.Component {
        state = {
            loading: false,
            imageUrl: null
        }

        beforeUpload = file => {
    //   const { file, type } = payload;
            const { dispatch } = this.props
            
            console.log(file)
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('You can only upload JPG/PNG file!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('Image must smaller than 2MB!');
            }

            dispatch({
                type: 'global/imageUpload',
                payload: {
                    file,
                    type: file.type
                }
            }).then(res => {
                console.log(res)
                if (res) {
                    this.setState({
                        imageUrl: res.url
                    })
                }
            })

            return isJpgOrPng && isLt2M;
        }

        handleChange = info => {
            if (info.file.status === 'uploading') {
                this.setState({ loading: true });
                return;
              }
              if (info.file.status === 'done') {
                // Get this url from response in real world.
                // getBase64(info.file.originFileObj, imageUrl =>
                  this.setState({
                    // imageUrl,
                    loading: false,
                  })
                // );
              }
        }

        render() {
            const formItemLayout = {
                labelCol: { span: 10 },
                wrapperCol: { span: 14 },
            }
            const { visible, onCancel, onCreate, form } = this.props
            const { getFieldDecorator } = form

            return (
                <Modal
                    visible={visible}
                    title="添加产品"
                    width='60%'
                    onCancel={onCancel}
                    onOk={onCreate}
                    style={{top: '33px'}}
                >
                    <Form className={styles.loginForm} style={{width: '85%'}}>
                        <Form.Item label="产品名称及型号" {...formItemLayout} required={false}>
                            {getFieldDecorator('product', {
                                rules: [{ required: true, message: '请输入产品名称及型号!'}],
                            })(<Input placeholder="请输入产品名称及型号"/>)}
                        </Form.Item>
                        <Form.Item label="产品图片" {...formItemLayout} required={false}>
                            {getFieldDecorator('images_url', {
                                rules: [{ required: true, message: '请上传产品图片!'}],
                            })(
                                <Upload 
                                    name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                    beforeUpload={this.beforeUpload}
                                    onChange={this.handleChange}
                                >
                                    <span className={styles.antUploadTextHa}>建议图片为100kb以上的清晰图，支持jpg，jpeg，png，gif等格式。</span>
                                    {
                                        this.state.imageUrl ? 
                                         
                                        <div>
                                            <div className={styles.antUploadText}>
                                                <img src={this.state.imageUrl} alt="avatar" style={{ width: '100%' }} />
                                            </div>
                                        </div>
                                        :
                                        <div>
                                            <Icon type={this.state.loading ? 'loading' : 'plus'} />
                                            <div className={styles.antUploadText}>添加图片</div>
                                        </div>
                                    }
                                    
                                </Upload>
                            )}
                        </Form.Item>
                        <Form.Item label="年销售额（万元）" {...formItemLayout} required={false}>
                            {getFieldDecorator('sales', {
                                rules: [{ required: true, message: '请输入产品2018年的销售额!'}],
                            })(<Input placeholder="请输入产品2018年的销售额"/>)}
                        </Form.Item>
                        <Form.Item label="占主营业务收入比重（%）" {...formItemLayout} required={false}>
                            {getFieldDecorator('proportion', {
                                rules: [{ required: true, message: '请输入产品占主营业务收入比重!'}],
                            })(<Input placeholder="请输入产品占主营业务收入比重"/>)}
                        </Form.Item>
                        <Form.Item label="主要面向市场" {...formItemLayout} required={false}>
                            {getFieldDecorator('market', {
                                rules: [{ required: true, message: '请输入产品主要面向的市场!'}],
                            })(<Input placeholder="请输入产品主要面向的市场"/>)}
                        </Form.Item>
                        <Form.Item label="产品功能介绍" {...formItemLayout} required={false}>
                            {getFieldDecorator('introduce', {
                                rules: [{ required: true, message: '请介绍产品主要功能!'}],
                            })(<Input.TextArea rows="4" placeholder="请介绍产品主要功能"/>)}
                        </Form.Item>
                        <Form.Item label="是否首台套" {...formItemLayout} required={false}>
                            {getFieldDecorator('isshouantai', {
                                rules: [{ required: true, message: '是否首台套!'}],
                            })(
                                <Radio.Group onChange={this.onChange} value={1}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group>
                            )}
                        </Form.Item>
                        <Form.Item label="是否有产品专利" {...formItemLayout} required={false}>
                            {getFieldDecorator('iszhuanli', {
                                rules: [{ required: true, message: '请选择!'}],
                            })(
                                <Radio.Group onChange={this.onChange} value={1}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group>  
                            )}
                        </Form.Item>
                        <Form.Item label="产品所属类型" {...formItemLayout} required={false}>
                            {getFieldDecorator('product_type', {
                                rules: [{ required: true, message: '请选择!'}],
                            })(
                                <Select placeholder="请选择">
                                    {children}
                                </Select>
                            )}
                        </Form.Item>
                    </Form>
                </Modal>
            )
        }
    }
)


@connect(({ golbal }) => ({
    golbal
}))


// eslint-disable-next-line react/prefer-stateless-function
class ImpoProduct extends Component {
    state = {
        visible: false,
        // status记录新增产品 1 或编辑产品状态 0 
        status: 1,
        // 编辑产品的key
        editKey: '',
        columns: [
            // {
            //     title: '序号',
            //     dataIndex: 'index',
            //     align: 'center',
            //     className: styles.tableColumBg,
            //     width: 70

            // },
            {
                title: '产品名称及型号',
                dataIndex: 'product',
                align: 'center',
                width: 150
            },
            {
                title: '产品主图',
                dataIndex: 'product_url',
                align: 'center',
                render: record => (
                    <img src={record} alt="" style={{width: '120px', height: '100px'}}/>
                ),
            },
            {
                title: '年销售额',
                dataIndex: 'sales',
                align: 'center'
            },
            {
                title: '占主营业务收入比重',
                dataIndex: 'proportion',
                align: 'center',
                width: 110,
            },
            {
                title: '主要面向市场',
                dataIndex: 'market',
                align: 'center',
                width: 110
            },
            {
                title: '产品功能介绍',
                dataIndex: 'introduce',
                align: 'center',
                width: '18%'
            },
            {
                title: '是否首台案',
                dataIndex: 'isshouantai',
                align: 'center',
                width: 90,
                render: (_, record) => (
                    <>
                      <span>{record.isshouantai ? '是' : '否'}</span>
                    </>
                ),
            },
            {
                title: '是否有产品专利',
                dataIndex: 'iszhuanli',
                align: 'center',
                width: 90,
                render: (_, record) => (
                    <>
                      <span>{record.iszhuanli ? '是' : '否'}</span>
                    </>
                ),
            },
            {
                title: '产品所属类型（参考备注）',
                dataIndex: 'product_type',
                align: 'center',
                width: 170
            },
            {
                title: '操作',
                dataIndex: 'address',
                align: 'center',
                width: 85,
                render: (_, record) => (
                    <>
                        <a style={{display: 'block', marginBottom: '10px'}}
                            onClick={() => this.editShowModal(record)}
                        >编辑</a>
                        <Popconfirm
                            title="你确定要删除吗？"
                            onConfirm={() => this.deleteOptions(record)}
                            okText="是"
                            cancelText="否"
                        >
                            <a href="#">删除</a>
                        </Popconfirm>
                    </>
                ),
            },
        ],
        showColumns: [
            {
                title: '序号',
                dataIndex: 'index',
                align: 'center',
                className: styles.tableColumBg,
                width: 70

            },
            {
                title: '产品名称及型号',
                dataIndex: 'product',
                align: 'center',
                width: 150
            },
            {
                title: '产品主图',
                dataIndex: 'product_url',
                align: 'center',
                render: record => (
                    <img src={record} alt="" style={{width: '120px', height: '100px'}}/>
                ),
            },
            {
                title: '年销售额',
                dataIndex: 'sales',
                align: 'center'
            },
            {
                title: '占主营业务收入比重',
                dataIndex: 'proportion',
                align: 'center',
                width: 110,
            },
            {
                title: '主要面向市场',
                dataIndex: 'market',
                align: 'center',
                width: 110
            },
            {
                title: '产品功能介绍',
                dataIndex: 'introduce',
                align: 'center',
                width: '18%'
            },
            {
                title: '是否首台案',
                dataIndex: 'isshouantai',
                align: 'center',
                width: 90,
                render: (_, record) => (
                    <>
                      <span>{record.isshouantai ? '是' : '否'}</span>
                    </>
                ),
            },
            {
                title: '是否有产品专利',
                dataIndex: 'iszhuanli',
                align: 'center',
                width: 90,
                render: (_, record) => (
                    <>
                      <span>{record.iszhuanli ? '是' : '否'}</span>
                    </>
                ),
            },
            {
                title: '产品所属类型（参考备注）',
                dataIndex: 'product_type',
                align: 'center',
                width: 170
            },
        ],
    }

    // 新增产品
    createShowModal = () => {
        const { form } = this.formRef.props
        form.resetFields()
        this.setState({
            status: 1,
            visible: true
        })
    }

    // 编辑产品
    editShowModal = record => {
        this.editKey = record.key
        const { form } = this.formRef.props
        this.setState({ 
            status: 0,
            visible: true,
            editKey: record.key
        })
        form.setFieldsValue({
            ...record
        })
    }

    // 删除产品
    deleteOptions = record => {
        const { deleteClick } = this.props
        deleteClick(record.key)
    }

    handleCreate = () => {
        const { form } = this.formRef.props
        const { confirm } = this.props
        // 判断编辑还是新增
        // 新增
        if (this.state.status) {
            form.validateFields((err, values) => {
                if (err) { return; }
                confirm(values, 'add')
                this.setState({ visible: false })
            })
            return;
        }
        // 编辑
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            // confirm(values)
            confirm(values, 'edit', this.state.editKey)
            this.setState({ visible: false })
        })
    }

    handleCancel = () => { this.setState({ visible: false }) }

    saveFormRef = formRef => { this.formRef = formRef }

    render () {
        const { type } = this.props
        const { dispatch } = this.props

        const EditHead = () => {
            if (type === 'edit') {
                return (
                    <Card
                        className={styles.basicHeadLayout}
                        bordered={false}
                    >
                        <div className={styles.headName}>三、主营产品</div>
                        <Button type="primary" onClick={this.createShowModal}>添加</Button>
                    </Card>
                )
            }
            return (<></>)
        }

        return (
            <>
                <EditHead />
                <Card bordered={false} className={styles.publicContent}>
                    <Table
                        columns={ type === 'edit' ? this.state.columns : this.state.showColumns}
                        dataSource={this.props.data}
                        bordered
                        pagination={ type === 'edit' ? { defaultPageSize: 2 } : false }
                    />
                </Card>
                <EditModal 
                    wrappedComponentRef={this.saveFormRef}
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    onCreate={this.handleCreate}
                    dispatch={dispatch}
                />
            </>
            
        )
    }
}

// eslint-disable-next-line react/prefer-stateless-function
export default ImpoProduct